#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>
//#define QT_NO_DEBUG_OUTPUT

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    jxlencoder=new jxlEncoder();
    jxldecoder=new jxlDecoder();

    connect(jxlencoder,&jxlEncoder::convertLog,this,&MainWindow::encoderLog);
    connect(jxlencoder,&jxlEncoder::convertResult,this,&MainWindow::encoderResult);

    connect(jxldecoder,&jxlDecoder::convertLog,this,&MainWindow::decoderLog);
    connect(jxldecoder,&jxlDecoder::convertResult,this,&MainWindow::decoderResult);

    inputWidget<<ui->clearList<<ui->frame;

    inputWidget_3<<ui->clearList_3<<ui->frame_3;

    //设置当前电脑cpu线程数为最多线程数
    int CpuCoreCount=QThread::idealThreadCount();
    if(CpuCoreCount!=-1){
        ui->CpuCoreUsage->setRange(1,CpuCoreCount);
        ui->CpuCoreUsage->setValue(CpuCoreCount);
    }
    else{//即使没有查到，最少也有1线程
        ui->CpuCoreUsage->setRange(1,1);
        ui->CpuCoreUsage->setValue(1);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::encoderResult(int num,int result)//显示转换结果
{
    if(result==1)
    {
        ui->inputListWidget->item(num)->setBackground(QBrush("Green"));//成功
    }
    else if(result==0)
    {
        ui->inputListWidget->item(num)->setBackground(QBrush("Red"));//失败
        errTaskNum++;
    }
    else {
        ui->inputListWidget->item(num)->setBackground(QBrush("Yellow"));//文件验证失败
        errTaskNum++;
    }
    ui->inputListWidget->scrollToItem(ui->inputListWidget->item(num));//滚动列表
    TaskNum++;

    ui->workState->setText("转换中:"+QString::number(TaskNum)+"/"+QString::number(inputFileList.size())
                           +"  失败:"+QString::number(errTaskNum));//显示转换进度

    //qDebug()<<num<<inputFileList.size();
    //任务完成，解锁操作区域
    if(TaskNum>inputFileList.size()-1){
        for (auto item:inputWidget) {
            item->setEnabled(true);
        }
    }
}

void MainWindow::encoderLog(QString log)//输出日志
{
    ui->plainTextEdit->appendPlainText(log);
}


void MainWindow::on_select_clicked()//选择输入图片
{
    QStringList filenames = QFileDialog::getOpenFileNames(this,tr("选择图片"),
                                                          "",
                                                          tr(" JPEG(*.jpg *.jpeg) ;;  所有文件(*.*)"));

    if(!filenames.isEmpty()){
        ui->inputListWidget->clear();
        ui->inputListWidget->addItems(filenames);
        inputFileList=filenames;
    }

}


void MainWindow::on_startEncode_clicked(bool checked)//点击开始转换
{
    if(jxlencoder->state()!=0||inputFileList.isEmpty()){
        return;//正在运行或列表为空 不响应
    }


    for (auto item:inputWidget) {
        item->setEnabled(false);//锁定操作按钮
    }

    ui->workState->setText("");//清空转换进度
    errTaskNum=0;//清空报错计数
    for(int ii=0;ii<ui->inputListWidget->count();ii++) {
        ui->inputListWidget->item(ii)->setBackground(Qt::white);
    }//重置转换列表颜色


    QString compressLevel=QString::number(ui->compressLevel->value());

    QStringList outputFilelist;
    QStringList parameterList;

    for(int ii=0;ii<inputFileList.size();ii++)
    {
        QString output;
        QString input=inputFileList.at(ii);

        QStringList temp;
        if(ui->outPutToSource->isChecked()){

            temp = input.split(".");
            if(temp.size()>1)
                temp.removeLast();//去除后缀
            output=temp.join(".");
        }
        else{
            QString temp1;
            temp1=input.split("/").last();//提取文件名
            temp= temp1.split(".");
            if(temp.size()>1)
                temp.removeLast();//去除后缀
            output=temp.join(".");
            output.prepend(ui->outPutPathEdit->text()+"/");
        }
        output.append(".jxl");//增加后缀

        outputFilelist.append(output);
        parameterList.append(" --effort "+compressLevel+" "+ui->customCommand->text());
        //qDebug()<<input<<"&"<<outputName;

    }

    bool deleteSource=ui->deleteSource->isChecked();//转换成功删除原始文件
    bool reverify =ui->HashVerify->isChecked();
    int coreUsage=ui->CpuCoreUsage->value();

    //发送输入输出文件列表以及参数，如果返回true，说明任务被接受，重置主界面的转换计数
    if(jxlencoder->inputTask(inputFileList,outputFilelist,parameterList,deleteSource,reverify,coreUsage)==true){

        TaskNum=0;
    }


    //    if(checked){
    //        ui->startEncode->setText("停止转换");
    //        for (auto item:inputWidget) {
    //            item->setEnabled(false);//锁定操作按钮
    //        }
    //    }else {
    //        ui->startEncode->setText("开始转换");
    //        for (auto item:inputWidget) {
    //            item->setEnabled(true);
    //        }
    //    }

}


void MainWindow::on_clearList_clicked()//清除输入列表
{
    ui->inputListWidget->clear();
    inputFileList.clear();

}

void MainWindow::on_clearLog_clicked()//清除日志
{
    ui->plainTextEdit->clear();
}


void MainWindow::on_outPutToSource_toggled(bool checked)//输入到原文件夹联动
{
    ui->outPutPath->setEnabled(!checked);
    ui->outPutPathEdit->setEnabled(!checked);
}


void MainWindow::on_outPutPath_clicked()//输出路径选择
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                    "/home",
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);
    if(!dir.isEmpty())
        ui->outPutPathEdit->setText(dir);
}

//==========================jxl转jpg===========================
void MainWindow::on_select_3_clicked()//选择输入图片
{
    QStringList filenames = QFileDialog::getOpenFileNames(this,tr("选择图片"),
                                                          "",
                                                          tr(" JXL(*.jxl) ;;  所有文件(*.*)"));

    if(!filenames.isEmpty()){
        ui->inputListWidget_3->clear();
        ui->inputListWidget_3->addItems(filenames);
        inputFileList_3=filenames;
    }
}


void MainWindow::decoderResult(int num,int result)//显示转换结果
{
    if(result==1)
    {
        ui->inputListWidget_3->item(num)->setBackground(QBrush("Green"));//成功
    }
    else {
        ui->inputListWidget_3->item(num)->setBackground(QBrush("Red"));//失败
        errTaskNum_3++;
    }
    ui->inputListWidget_3->scrollToItem(ui->inputListWidget_3->item(num));//滚动列表

    ui->workState_3->setText("转换中:"+QString::number(num+1)+"/"+QString::number(inputFileList_3.size())
                             +"  失败:"+QString::number(errTaskNum_3));//显示转换进度

    //任务完成，解锁操作区域
    if(num>=inputFileList_3.size()-1){
        for (auto item:inputWidget_3) {
            item->setEnabled(true);
        }
    }
}

void MainWindow::decoderLog(QString log)//输出日志
{
    ui->plainTextEdit_3->appendPlainText(log);
}


void MainWindow::on_startEncode_3_clicked()//开始转换
{
    if(jxldecoder->state()!=0||inputFileList_3.isEmpty()){
        return;//正在运行或列表为空 不响应
    }
    for (auto item:inputWidget_3) {
        item->setEnabled(false);//锁定操作按钮
    }

    ui->workState_3->setText("");//清空转换进度
    errTaskNum_3=0;
    for(int ii=0;ii<ui->inputListWidget_3->count();ii++) {
        ui->inputListWidget_3->item(ii)->setBackground(Qt::white);
    }//重置转换列表颜色

    QStringList outputFilelist;
    QStringList parameterList;

    for(int ii=0;ii<inputFileList_3.size();ii++)
    {
        QString output;
        QString input=inputFileList_3.at(ii);

        QStringList temp;
        if(ui->outPutToSource_3->isChecked()){

            temp = input.split(".");
            if(temp.size()>1)
                temp.removeLast();//去除后缀
            output=temp.join(".");
        }
        else{
            QString temp1;
            temp1=input.split("/").last();//提取文件名
            temp= temp1.split(".");
            if(temp.size()>1)
                temp.removeLast();//去除后缀
            output=temp.join(".");
            output.prepend(ui->outPutPathEdit_3->text()+"/");
        }
        output.append(".jpg");//增加后缀

        outputFilelist.append(output);
        parameterList.append(ui->customCommand_3->text());
        //qDebug()<<input<<"&"<<outputName;

    }
    bool deleteSource=ui->deleteSource_3->isChecked();//转换成功删除原始文件
    if(jxldecoder->inputTask(inputFileList_3,outputFilelist,parameterList,deleteSource)==true){


    }


}


void MainWindow::on_clearList_3_clicked()
{
    ui->inputListWidget_3->clear();
    inputFileList_3.clear();
}


void MainWindow::on_clearLog_3_clicked()
{
    ui->plainTextEdit_3->clear();
}


void MainWindow::on_outPutPath_3_clicked()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                    "/home",
                                                    QFileDialog::ShowDirsOnly
                                                    | QFileDialog::DontResolveSymlinks);
    if(!dir.isEmpty())
        ui->outPutPathEdit_3->setText(dir);
}


void MainWindow::on_outPutToSource_3_toggled(bool checked)//输入到原文件夹联动
{
    ui->outPutPath_3->setEnabled(!checked);
    ui->outPutPathEdit_3->setEnabled(!checked);
}



